Page({
  data: {
    schema:[
    ],
    formData:{
    },
    title: '',
    result: '',
    remark: '',
    apiName: '',
    hceState: 'unknown', // unknown, running, stopped
    stateMessage: '未检查HCE状态',
    messageToSend: 'A00102030405' // 示例消息，十六进制格式
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })
    
    this.setData({
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
    // 页面加载时检查HCE状态
    // this.checkHCEState();
  },
  /**
   * 检查HCE状态
   */
  checkHCEState(e) {
    const that = this;
    wx.getHCEState({
      success(res) {
        // 成功获取状态，说明HCE正在运行
        that.setData({
          hceState: 'running',
          stateMessage: 'HCE服务正在运行中',
          result: res,
          apiName: e.currentTarget.dataset.apiname
        });
        console.log('HCE状态：运行中', res);
      },
      fail(err) {
        // 获取状态失败，根据错误码判断原因
        let message = '';
        switch(err.errCode) {
          case 13000:
            message = '设备不支持NFC功能';
            break;
          case 13001:
            message = 'NFC功能未开启，请在系统设置中开启';
            break;
          case 13002:
            message = 'HCE功能未开启，请在微信权限中允许';
            break;
          case 13006:
            message = 'HCE服务未启动';
            break;
          default:
            message = `获取HCE状态失败：${err.errMsg}`;
        }
        
        that.setData({
          hceState: 'stopped',
          stateMessage: message,
          result: err,
          apiName: e.currentTarget.dataset.apiname
        });
        console.error('HCE状态错误：', err);
      }
    });
  },

  /**
   * 启动HCE服务
   */
  startHCE(e) {
    const that = this;
    // AID列表，需与读卡器约定
    const aidList = ['F222222222'];
    
    wx.startHCE({
      aid_list: aidList,
      success(res) {
        wx.showToast({
          title: 'HCE启动成功',
          icon: 'success'
        });
        that.setData({
          result: res,
          apiName: e.currentTarget.dataset.apiname
        })
        // 启动成功后重新检查状态
        // setTimeout(() => {
        //   that.checkHCEState();
        // }, 500);
      },
      fail(err) {
        wx.showToast({
          title: `启动失败：${err.errMsg}`,
          icon: 'none'
        });
        that.setData({
          result: err,
          apiName: e.currentTarget.dataset.apiname
        })
      }
    });
  },

  /**
   * 停止HCE服务
   */
  stopHCE(e) {
    const that = this;
    wx.stopHCE({
      success(res) {
        wx.showToast({
          title: 'HCE已停止',
          icon: 'success'
        });
        that.setData({
          result: res,
          apiName: e.currentTarget.dataset.apiname
        })
        // 停止成功后重新检查状态
        // setTimeout(() => {
        //   that.checkHCEState();
        // }, 500);
      },
      fail(err) {
        wx.showToast({
          title: `停止失败：${err.errMsg}`,
          icon: 'none'
        });
        that.setData({
          result: err,
          apiName: e.currentTarget.dataset.apiname
        })
      }
    });
  },
  sendHCEMessage(e){
    const that = this
    if(that.data.hceState=='unknown'){
      wx.showToast({ title: '请先启动HCE', icon: 'none' })
      return
    }
    const message = this.data.messageToSend
    if (!message) {
      wx.showToast({ title: '请输入消息', icon: 'none' })
      return
    }
    // 将十六进制字符串转换为ArrayBuffer
    const buffer = this.hexStringToArrayBuffer(message)
    
    wx.sendHCEMessage({
      data: buffer,
      success: (res) => {
        that.setData({
          result: res,
          apiName: e.currentTarget.dataset.apiname
        })
      },
      fail: (err) => {
        let errorMsg = '';
        switch (err.errCode) {
          case 13000:
            errorMsg = '设备不支持NFC';
            break;
          case 13001:
            errorMsg = 'NFC功能未开启';
            break;
          case 13002:
            errorMsg = 'HCE功能未开启';
            break;
          case 13006:
            errorMsg = 'HCE服务未启动';
            break;
          case 13007:
            errorMsg = '发送数据失败';
            break;
          default:
            errorMsg = `发送失败: ${err.errMsg}`;
        }
        that.setData({
          result: errorMsg,
          apiName: e.currentTarget.dataset.apiname
        })
      }
    })
  },
  // 十六进制字符串转ArrayBuffer
  hexStringToArrayBuffer(hexString) {
    hexString = hexString.replace(/\s/g, '')
    const buffer = new ArrayBuffer(hexString.length / 2)
    const dataView = new DataView(buffer)
    
    for (let i = 0; i < hexString.length; i += 2) {
      const value = parseInt(hexString.substr(i, 2), 16)
      dataView.setUint8(i / 2, value)
    }
    
    return buffer
  },
  onHCEMessage(e){
    const that = this;
    this.listener = wx.onHCEMessage((res) => {
      console.log(res)
      if (res.type === 'command') {
        that.setData({
          result: res,
          apiName: e.currentTarget.dataset.apiname
        })
      } else if (res.type === 'deactivated') {
        that.setData({ 
          hceState: 'stopped',
          result: res,
          apiName: e.currentTarget.dataset.apiname
        });
      }
    });
  },
  offHCEMessage(e){
    wx.offHCEMessage(this.listener)
    this.setData({
      result: "移除接收 NFC 设备消息事件的监听函数",
      apiName: e.currentTarget.dataset.apiname
    })
  },
})
